package cn.codesugar.multimedia

import android.annotation.SuppressLint
import android.media.MediaPlayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.SeekBar
import cn.codesugar.multimedia.databinding.ActivityPlayAudioTestBinding
import java.text.SimpleDateFormat
import java.util.*

class PlayAudioTestActivity : AppCompatActivity() {

    private var b: ActivityPlayAudioTestBinding? = null
    private var mediaPlayer = MediaPlayer()
    private var timer = Timer()
    private var duration = 0
    private var fromUser = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        b = ActivityPlayAudioTestBinding.inflate(layoutInflater)
        setContentView(b?.root)
        initMediaPlayer()
        timer.schedule(timerTask, 1, 1)
        b?.play?.setOnClickListener {
            // 判断当前MediaPlayer是否正在播放音频
            if (!mediaPlayer.isPlaying) {
                // 开始或继续播放音频
                mediaPlayer.start()
            }
        }
        b?.musicProgress?.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                Log.e("20210610", "onProgressChanged() progress:$progress, fromUser:$fromUser")
                this@PlayAudioTestActivity.fromUser = fromUser
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                Log.e("20210610", "onStartTrackingTouch()")
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                Log.e("20210610", "onStopTrackingTouch()")
                seekBar?.progress?.let { mediaPlayer.seekTo(it) }
                this@PlayAudioTestActivity.fromUser = false
            }

        })
        b?.pause?.setOnClickListener {
            if (mediaPlayer.isPlaying) {
                // 暂停播放音频
                mediaPlayer.pause()
            }
        }
        b?.stop?.setOnClickListener {
            if (mediaPlayer.isPlaying) {
                // 将MediaPlayer对象重置到刚刚创建的状态
                mediaPlayer.reset()
                initMediaPlayer()
            }
        }
    }

    /**
     * 加载媒体播放器
     */
    @SuppressLint("SetTextI18n")
    private fun initMediaPlayer() {
        val assetManager = assets
        val fd = assetManager.openFd("江南(完美推荐版)_林俊杰_128K.mp3")
        // 设置要播放的音频文件的位置
        mediaPlayer.setDataSource(fd.fileDescriptor, fd.startOffset, fd.length)
        // 在开始播放之前调用，以完成准备工作
        mediaPlayer.prepare()
        duration = mediaPlayer.duration // 获取时长
        b?.musicInfo?.text = "0:00/" + duration.toLong().toDateStr()
        b?.musicProgress?.max = duration
    }

    /**
     * 时间戳转换成字符窜
     * @param pattern 时间样式 yyyy-MM-dd HH:mm:ss
     * @return [String] 时间字符串
     */
    @SuppressLint("SimpleDateFormat")
    fun Long.toDateStr(pattern: String = "mm:ss"): String {
        val date = Date(this)
        val format = SimpleDateFormat(pattern)
        return format.format(date)
    }

    private val timerTask = object : TimerTask() {
        @SuppressLint("SetTextI18n")
        override fun run() {
            val currentPosition = mediaPlayer.currentPosition
            runOnUiThread {
                b?.musicInfo?.text = currentPosition.toLong().toDateStr() + "/" + duration.toLong().toDateStr()
                if (!fromUser) {
                    Log.e("20210610", "currentPosition:$currentPosition")
                    b?.musicProgress?.progress = currentPosition
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        timer.cancel()
        timer.purge()
        // 停止播放音频。调用后的MediaPlayer对象无法再播放音频
        mediaPlayer.stop()
        // 释放与MediaPlayer对象相关的资源
        mediaPlayer.release()
    }
}